<?php
/**
 * (jobs) AmazonSku销售关系
 */
namespace App\Jobs\Products;

use App\Models\Basics\AmazonAccount;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\ExchangeRate;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysICountry;
use App\Models\Basics\Transport;
use App\Models\MonthlyReport\Cost\LogisticsBasics;
use App\Models\Operation\ProfitSku;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductAmazonSkuCCS;
use App\Models\Product\ProductPacking;
use App\Models\Product\ProductSku;
use App\Models\SsBasic\AreaSku;
use App\Models\SsBasic\CountrySku;
use App\Models\Stocking\StockingSetDate;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class AmazonSkuSRelate implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $productAmazonSkus;

    protected $userId;

    /**
     * AmazonSkuRelates constructor.
     * @param $productAmazonSkus
     * @param $userId
     */
    public function __construct($productAmazonSkus,$userId)
    {
        $this->productAmazonSkus = $productAmazonSkus;
        $this->userId = $userId;
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle()
    {
        $this->exeFillData($this->productAmazonSkus,$this->userId);
    }

    private function exeFillData($productAmazonSkus,$userId){
        $key1 = [];//在售状态
        $key2 = [];//泛欧
        $key3 = [];//销售
        $key4 = [];//毛利率
        $key5 = [];// 备货，提货(站点)
        $key5_1 = [];// 备货，提货(国家)
        $key6 = [];// 备货日期设置
        $area = [];
        $price = [];
        $vat = [];
        $pCycle = [];
        $pCycleForSetDate = [];// 备货日期设置
        $countryForSetDate = [];// 备货日期设置
        $seaDayArrForSetDate = [];// 备货日期设置
        $transportArr = [];
        $shipmentTransportArr = [];
        $shipmentArr = [];
        $avgFeeArr = [];
        $rateOddsArr = [];
        $country = AmazonCountry::options(['fan_eu' => 1]);
        $countryIdsForFanEU = array_keys($country->toArray());
        $notInAccountId = AmazonAccount::$_notFanEu;
        foreach ($productAmazonSkus as $productAmazonSku){
            $sku = ProductSku::getModelById($productAmazonSku->psku_id);
            if(!array_key_exists($productAmazonSku->psku_id,$price)){
                $price[$productAmazonSku->psku_id] = ProductSku::getPuPriceNoTax($sku);
            }
            if(!in_array($productAmazonSku->psku_id,$key1)){
                $sku->is_sales = 1;
                $sku->save();//更新产品表在售状态
                $key1[] = $productAmazonSku->psku_id;
            }
            if(!array_key_exists($productAmazonSku->country_id,$vat)){
                $vat[$productAmazonSku->country_id] = AmazonCountry::getVatByCountryId($productAmazonSku->country_id);
            }
            if(in_array($productAmazonSku->country_id,$countryIdsForFanEU) && (!in_array($productAmazonSku->account_id,$notInAccountId))){
                $_key2 = $productAmazonSku->seller_sku.'_'.$productAmazonSku->child_asin.'_'.$productAmazonSku->fnsku;
                if(!in_array($_key2,$key2)){
                    $key2[] = $_key2;
                }
            }
            $_key3 = $productAmazonSku->country_id.'_'.$sku->classify_id;//seller_id_key
            if(!array_key_exists($_key3,$key3)){
                $ccs = ProductAmazonSkuCCS::returnSellerId($productAmazonSku->country_id,$sku->classify_id,$userId);
                $key3[$_key3] = $ccs->seller_id ?? $userId;
            }
            //更新销售
            $productAmazonSku->seller_id = $key3[$_key3];
            $productAmazonSku->save();
            if(!array_key_exists($productAmazonSku->country_id,$area)){
                $area[$productAmazonSku->country_id] = SysICountry::getAreaIdByCountryId($productAmazonSku->country_id);
            }
            if(!array_key_exists($productAmazonSku->psku_id,$pCycle)){
                $pCycle[$productAmazonSku->psku_id] = ProductSku::getPuCycle($sku);
            }
            $areaId = $area[$productAmazonSku->country_id];
            if(!array_key_exists($areaId,$transportArr)){
                $_transport = Transport::getTransport($areaId);
                $transportArr[$areaId] = $_transport ?: null;
            }
            $shipmentKey = $areaId.'_'.$productAmazonSku->psku_id;
            if(!array_key_exists($shipmentKey,$avgFeeArr)){
                $shipmentCount = LogisticsBasics::countLastLogistics($areaId,$productAmazonSku->psku_id);
                $avgFeeArr[$shipmentKey] = $shipmentCount > 0 ? true : false;
            }
            $avgFee = $avgFeeArr[$shipmentKey];
            if($avgFee){
                if(!array_key_exists($shipmentKey,$shipmentArr)){
                    $shipmentArr[$shipmentKey] = LogisticsBasics::getLastLogistics($areaId,$productAmazonSku->psku_id);
                }
            }else{
                if(!array_key_exists($areaId,$shipmentTransportArr)){
                    $_transport1 = Transport::getTransport($areaId);
                    $shipmentTransportArr[$areaId] = $_transport1 ?: null;
                }
            }
            $_key4 = $productAmazonSku->country_id.'_'.$productAmazonSku->psku_id;
            if(!in_array($_key4,$key4)){
                if(!array_key_exists($productAmazonSku->country_id,$rateOddsArr)){
                    $currencyCode = AmazonCountry::getCurrencyCodeByCountryId($productAmazonSku->country_id);
                    $_rateOdds = ExchangeRate::getRateOddsToRMB($currencyCode,time());
                    $rateOddsArr[$productAmazonSku->country_id] = $_rateOdds;
                }
                $rateOdds = $rateOddsArr[$productAmazonSku->country_id];
                if($avgFee){
                    $shipment = $shipmentArr[$shipmentKey];
                    $airFee = $seaFee = $shipment->price;
                }else{
                    $transport1 = $shipmentTransportArr[$areaId];
                    $airFee = $transport1 ? $transport1->air_fee : 0;
                    $seaFee = $transport1 ? $transport1->sea_fee : 0;
                }
                $shipWeight = ProductPacking::getShipWeight($productAmazonSku->psku_id);
                $tplRMB = $price[$productAmazonSku->psku_id];
                $_vat = $vat[$productAmazonSku->country_id];
                ProfitSku::addProfitSku($productAmazonSku,$rateOdds,$tplRMB,$shipWeight,$airFee,$seaFee,$_vat,$avgFee);
                $key4[] = $_key4;
            }
            //备货站点
            $_key5 = $areaId.'_'.$productAmazonSku->psku_id;
            if(!in_array($_key5,$key5)){
                $key5[] = $_key5;
            }
            //备货国家（EU）
            if ($areaId == 4) {
                $_key5_1 = $productAmazonSku->country_id.'_'.$productAmazonSku->psku_id;
                if(!in_array($_key5_1,$key5_1)){
                    $key5_1[] = $_key5_1;
                }
            }
            // 备货日期设置
            $_key6 = $areaId.'_'.$sku->classify_id;
            if(!array_key_exists($areaId,$countryForSetDate)){
                $countryForSetDate[$areaId] = SysICountry::getCountryIdsByAreaId($areaId);
            }
            $countryIds = $countryForSetDate[$areaId];
            if(!array_key_exists($_key6,$pCycleForSetDate)){
                $pCycleForSetDate[$_key6] = StockingSetDate::getPCycle($countryIds,$sku->classify_id);
            }
            if(!array_key_exists($areaId,$seaDayArrForSetDate)){
                $transportForSetDate = $transportArr[$areaId];
                $seaDayArrForSetDate[$areaId] = $transportForSetDate ? $transportForSetDate->sea_day : 0;
            }
            if(!in_array($_key6,$key6)){
                $key6[] = $_key6;
            }
        }
        $this->_upTimes($key2,$countryIdsForFanEU,$notInAccountId);
        $this->_addAreaSku($key5,$transportArr,$pCycle,$price);
        $this->_addCountrySku($key5_1,$transportArr,$pCycle,$price);
        $this->_addSetDate($key6,$pCycleForSetDate,$seaDayArrForSetDate);// 备货日期设置
    }

    /**
     * 标记泛欧状态
     * @param $fanEuItems
     * @param $countryIdsForFanEU
     * @param $notInAccountId
     */
    private function _upTimes($fanEuItems,$countryIdsForFanEU,$notInAccountId){
        foreach ($fanEuItems as $fanEuItem){
            list($sellerSku,$childAsin,$fnSku) = explode('_',$fanEuItem);
            ProductAmazonSku::upTimes($sellerSku,$childAsin,$fnSku,$countryIdsForFanEU,$notInAccountId);
        }
    }

    /**
     * 添加备货，提货基础数据（站点）
     * @param $areaSkuItems
     * @param $transportArr
     * @param $pCycle
     * @param $price
     */
    private function _addAreaSku($areaSkuItems,$transportArr,$pCycle,$price){
        if ($areaSkuItems) {
            foreach ($areaSkuItems as $areaSkuItem){
                list($areaId,$pSkuId) = explode('_',$areaSkuItem);
                $transport = $transportArr[$areaId];
                if($transport){
                    $airDay = $transport->air_day;
                    $seaDay = $transport->sea_day;
                }else{
                    $airDay = 0;
                    $seaDay = 0;
                }
                //备货站点sku
                AreaSku::addAreaSku($areaId,$pSkuId,$airDay,$seaDay,$pCycle[$pSkuId],$price[$pSkuId]);
            }
        }
    }

    /**
     * 添加备货，提货基础数据（国家）
     * @param $countrySkuItems
     * @param $transportArr
     * @param $pCycle
     * @param $price
     */
    private function _addCountrySku($countrySkuItems,$transportArr,$pCycle,$price){
        if ($countrySkuItems) {
            foreach ($countrySkuItems as $countrySkuItem){
                list($countryId,$pSkuId) = explode('_',$countrySkuItem);

                $areaId = SysCountry::getAreaIdByCountryId($countryId); //查询国家归属地区（站点）
                $transport = $transportArr[$areaId];
                if($transport){
                    $airDay = $transport->air_day;
                    $seaDay = $transport->sea_day;
                }else{
                    $airDay = 0;
                    $seaDay = 0;
                }
                //备货国家sku
                CountrySku::addCountrySku($countryId,$pSkuId,$airDay,$seaDay,$pCycle[$pSkuId],$price[$pSkuId]);
            }
        }
    }

    /**
     * 添加备货设置日期记录
     * @param $setDateItems
     * @param $pCycle
     * @param $seaDayArr
     */
    private function _addSetDate($setDateItems,$pCycle,$seaDayArr){
        foreach ($setDateItems as $setDateItem){
            list($areaId,$classifyId) = explode('_',$setDateItem);
            StockingSetDate::addSetDate($areaId,$classifyId,$pCycle[$setDateItem],$seaDayArr[$areaId]);
        }
    }
}
